For Simple variable or single or scalar variable we store 1 single value at a certain address
Note: for our discussion we take 2 bytes per integer (it may be 4 b
int x = address 200 to 201, (if assume 2 bytes per integer)
An array store multiple (e.g 5) will store data of same type.
int x[5] = address 200 - 209 = 10 bytes (if we assume 2 bytes per integer)
Differentiate values with the use of index, A[1]
Picture
With only declaration, then empty array will have garbage values.
Can only initialise a few values or single value, rest will be initialised with zero
int A[5]={1,2};
int A[5]={0}
Don't have to give a size, it will get size from count of values:
int A[]={1,2,3,4,5}
int A[5]={1,2,3,4,5}
int *p=&A;
for (int i; i<4; i++){
cout<<A[i]<<endl
}
or
for (int i; i<5; i++){
cout<<i[A]<<endl
}
or use pointer
for (int i; i<5; i++){
cout<<*p[i]<<endl
}
Static means the size is fixed, or Dynmaic means the size is not fixed
By default array is located or created in stack.
To create a dynamic array, we need to create a pointer with new keyword.
int A[5];
int p*;
p=new int [5]
The second array has nothing to do with A array.
The pointer is declare in STACK, but the array is created in HEAP
But we must delete (deallocated) or release memory when not required
delete []p
p = nullptr
p[2]=7;
So the pointer acts as NAME for the array. There is no other name for the array.
To increase the size of array?
How to we do this.
we cannot increase the existing array. But we can create a new pointer to new array with bigger size. Move all the contents of the old array to the new array. Delete old pointer to array. set the new pointer to old pointer of bigger array.
The main idea: Create a new HEAP array pointer, and then point the old array to this new array.
Remember we cannot increase the size of existing array.
Additional picture